package com.hdyg.sixg.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hdyg.sixg.R;
import com.hdyg.sixg.activity.common.AppManager;
import com.hdyg.sixg.activity.common.BaseActivity;
import com.hdyg.sixg.app.MvpApplication;
import com.hdyg.sixg.mvp.base.BaseUrl;
import com.hdyg.sixg.mvp.base.SpMsg;
import com.hdyg.sixg.ui.MyWebView;
import com.hdyg.sixg.util.AlertDialogUtil;
import com.hdyg.sixg.util.JavaScriptinterface;
import com.hdyg.sixg.util.LogUtils;
import com.hdyg.sixg.util.SPUtils;
import com.hdyg.sixg.util.TakePhotoUtil;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import java.io.File;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Cookie;

/**
 * @author CZB
 * @describe 网页
 * @time 2019/4/19 10:34
 */

public class WebActivity extends BaseActivity {

    @BindView(R.id.webView)
    MyWebView mWebView;
    @BindView(R.id.ll_top_left)
    LinearLayout llTopLeft;
    @BindView(R.id.tvTopTitle)
    TextView tvTopTitle;

    private String URL;//传递的URL
    private boolean isCertain = false;
    private final int scanQrCodeRequestCode = 0x1100;//扫描回调
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private String desCpt, failUrl;
    private boolean GUIDE_FLAG = true;
    private boolean SELECT_IMG = false; //是否选择图片 默认不选择


    @Override
    protected int getLayoutId() {
        return R.layout.activity_web;
    }

    @Override
    protected void initView() {
        URL = getIntent().getStringExtra(SpMsg.URL);
        GUIDE_FLAG = getIntent().getBooleanExtra(SpMsg.INTENT_STR, true);
        mWebView.loadUrl(URL);
        initWebView();
        mWebView.addJavascriptInterface(new JavaScriptinterface(mContext, mWebView), "android");
    }


    /**
     * 同步一下cookie
     */
    public void synCookies(String url) {
        Cookie sessionCookie = MvpApplication.cookie;    //这里的cookie就是上面保存的cookie
        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        if (sessionCookie != null) {
            cookieManager.removeSessionCookie();
            String cookieString = sessionCookie.name() + "=" + sessionCookie.value() + "; domain=" + sessionCookie.domain();
            cookieManager.setCookie(url, cookieString);
            Log.d("czb", cookieString);
            CookieSyncManager.getInstance().sync();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtils.d("url====>" + url);
                if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("HTTP:") || url.startsWith("HTTPS:")) {
                    view.loadUrl(url);
                    return false;
                } else if (BaseUrl.LOGOUT.equals(url)) {
                    //token失效 - 退出登录
                    String token = SPUtils.get(SpMsg.TOKEN, "");
                    String str = "";
                    if (TextUtils.isEmpty(token)) {
                        str = "还未登录，请先登录！";
                    } else {
                        str = "token过期或已失效，请重新登录!";
                    }
                    AlertDialogUtil.getInstance().showDialog(mContext, "警告", str, new AlertDialogUtil.OnClickYesListener() {
                        @Override
                        public void onClickYes() {
                            AppManager.getAppManager().staLoginActivity();
                        }
                    }, new AlertDialogUtil.OnClickNoListener() {
                        @Override
                        public void onClickNo() {

                        }
                    }, false);
                    return true;
                } else if (BaseUrl.LOGOUT2.equals(url)) {
                    //主动退出登录
                    AppManager.getAppManager().staLoginActivity();
                    return true;
                } else if (BaseUrl.SET_BACK.equals(url)) {
                    //后退
                    if (GUIDE_FLAG) {
                        if (mWebView.canGoBack()) {
                            mWebView.goBack();
                        } else {
                            finish();
                        }
                    } else {
                        startActivity(MainActivity.class);
                    }

                    return true;
                } else if (url.contains("tel:")) {
                    //拨打电话
                    Uri uri = Uri.parse(url);
                    Intent mIntent = new Intent(Intent.ACTION_DIAL, uri);
                    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                        startActivity(mIntent);
                        return true;
                    } else {
                        ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.CALL_PHONE}, 1);
                        return true;
                    }
                } else if (url.startsWith("weixin://") || url.startsWith("alipays://") || url.startsWith("intent://") || url.startsWith("mqqapi://")) {
                    try {
                        mContext.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        if (url.startsWith("alipays://")) {
                            AlertDialogUtil.getInstance().showDialog(mContext, "温馨提示", "未检测到支付宝客户端，请请安装后重试!", new AlertDialogUtil.OnClickYesListener() {
                                @Override
                                public void onClickYes() {
                                    // 点击按钮所调用的方法
                                    Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                    mContext.startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                }
                            }, false);
                        }
                        return false;
                    }
                    return true;
                } else {
//                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                    startActivity(intent);
                    return true;
                }
            }

            //网络请求部分  去广告
//            @Override
//            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
////                LogUtils.d("网络请求部分--->"+url);
//                url = url.toLowerCase();
////                LogUtils.d("处理后的url--->"+url);
//                if (url.contains(BaseUrl.BaseUrl) || url.contains(BaseUrlUtil.BaseUpUrl) || url.contains(BaseUrlUtil.BaseUpUrl2)) {
//                    return super.shouldInterceptRequest(view, url);
//                } else {
//                    //去掉广告
//                    return new WebResourceResponse(null, null, null);
//                }
//            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                view.loadUrl("javascript:chaoS('" + desCpt + "','" + failUrl + "')");
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                view.loadUrl(BaseUrl.NET_FAIL_URL);
                desCpt = description;
                failUrl = failingUrl;
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsConfirm(WebView arg0, String arg1, String arg2,
                                       JsResult arg3) {
                return super.onJsConfirm(arg0, arg1, arg2, arg3);
            }

            View myVideoView;
            View myNormalView;
            CustomViewCallback callback;

            // /////////////////////////////////////////////////////////
            //

            /**
             * 全屏播放配置
             */
            @Override
            public void onShowCustomView(View view, CustomViewCallback customViewCallback) {
                FrameLayout normalView = (FrameLayout) findViewById(R.id.web_filechooser);
                ViewGroup viewGroup = (ViewGroup) normalView.getParent();
                viewGroup.removeView(normalView);
                viewGroup.addView(view);
                myVideoView = view;
                myNormalView = normalView;
                callback = customViewCallback;
            }

            @Override
            public void onHideCustomView() {
                if (callback != null) {
                    callback.onCustomViewHidden();
                    callback = null;
                }
                if (myVideoView != null) {
                    ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
                    viewGroup.removeView(myVideoView);
                    viewGroup.addView(myNormalView);
                }
            }

            // ======================== 自定义的window alert ============================
            @Override
            public boolean onJsAlert(WebView arg0, String arg1, String arg2,
                                     final JsResult arg3) {
                /**
                 * 这里写入你自定义的window alert
                 */
//                return super.onJsAlert(null, arg1, arg2, arg3);
                View view = LayoutInflater.from(mContext).inflate(R.layout.sys_window_alert, null);
                TextView title = (TextView) view.findViewById(R.id.title);
                TextView content = (TextView) view.findViewById(R.id.content);
                TextView certain = (TextView) view.findViewById(R.id.certain);
                // 实例化 AlertDialog
                final AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
                // 获取 AlertDialog 的窗体
                Window window = alertDialog.getWindow();
                // 设置背景透明
                window.setBackgroundDrawableResource(android.R.color.transparent);
                // 标题
                title.setText("温馨提示");
                // 内容
                content.setText(arg2);
                // 设置点击系统返回可以关闭
                alertDialog.setCancelable(true);
                // 显示
                alertDialog.show();
                // 加载布局，必须在 show 之后
                window.setContentView(view);
                // 点击事件
                certain.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isCertain = true;
                        alertDialog.dismiss();
                    }
                });
                alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (isCertain) {
                            arg3.confirm();
                        } else {
                            arg3.cancel();
                        }
                    }
                });

                return true;
            }
            // =============================== 弹窗 =======================================

            // =============================== 文件上传 ====================================

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                SELECT_IMG = true;
                mUploadCallbackAboveL = filePathCallback;
                TakePhotoUtil.getInstance().selectPhotoCropSingle(mContext, new TakePhotoUtil.OnTakePhotoListener() {
                    @Override
                    public void onSuccess(Object obj) {
                        SELECT_IMG = false;
                        File file = new File(obj.toString());
                        Uri result = Uri.fromFile(file);
                        if (mUploadMessage != null) {
                            mUploadMessage.onReceiveValue(Uri.parse(obj.toString()));
                            mUploadMessage = null;
                        }
                        if (mUploadCallbackAboveL != null) {
                            mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
                            mUploadCallbackAboveL = null;
                        }
                    }
                });
                return true;
            }

            /**
             * 获取标题的方法
             * @param view
             * @param title
             */
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (title != null) {
                    tvTopTitle.setText(title);
                }
            }

            // ======================================================================

        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            if (mUploadCallbackAboveL != null) {
                mUploadCallbackAboveL.onReceiveValue(null);
                mUploadCallbackAboveL = null;
            }
            return;
        }
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case scanQrCodeRequestCode://扫描回调
                //处理扫描结果（在界面上显示）
                if (null != data) {
                    Bundle bundle = data.getExtras();
                    if (bundle == null) {
                        return;
                    }
                    if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                        String scanQrCodeStr = data.getStringExtra(CodeUtils.RESULT_STRING);//扫码回调结果
                        LogUtils.d("扫描结果1==" + scanQrCodeStr);
                        scanQrCodeStr += "&&token=" + SPUtils.get("token", "");
                        LogUtils.d("扫描结果2==" + scanQrCodeStr);
                        Bundle b = new Bundle();
                        b.putString("url", scanQrCodeStr);
                        startActivity(WebActivity.class, b);

                    } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                        Toast.makeText(mContext, R.string.scan_qrcode_fail, Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (SELECT_IMG) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }
            if (mUploadCallbackAboveL != null) {
                mUploadCallbackAboveL.onReceiveValue(null);
                mUploadCallbackAboveL = null;
            }
        }
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.ll_top_left})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_top_left:
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
                break;
        }
    }

    @Override
    protected void createPresenter() {

    }

    /**
     * 系统返回键回退处理
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        } else {
            if (GUIDE_FLAG) {
                this.finish();
            } else {
                startActivity(MainActivity.class);
            }
            return true;
        }
    }

}
